package com.yl.immodule.util;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class TimeUtils {
    
    public static final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000;
    
    public static String formatTime(long timestamp) {
        Calendar now = Calendar.getInstance();
        Calendar msgTime = Calendar.getInstance();
        msgTime.setTimeInMillis(timestamp);
        
        // 格式化器
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd HH:mm", Locale.getDefault());
        SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
        
        // 判断是今天、昨天还是更早
        if (isSameDay(now, msgTime)) {
            return "今天 " + timeFormat.format(msgTime.getTime());
        } else if (isYesterday(now, msgTime)) {
            return "昨天 " + timeFormat.format(msgTime.getTime());
        } else if (isSameYear(now, msgTime)) {
            return dateFormat.format(msgTime.getTime());
        } else {
            return yearFormat.format(msgTime.getTime());
        }
    }
    
    private static boolean isSameDay(Calendar cal1, Calendar cal2) {
        return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
                cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);
    }
    
    private static boolean isYesterday(Calendar today, Calendar yesterday) {
        long diff = today.getTimeInMillis() - yesterday.getTimeInMillis();
        return diff < MILLIS_PER_DAY && 
                today.get(Calendar.DAY_OF_YEAR) != yesterday.get(Calendar.DAY_OF_YEAR);
    }
    
    private static boolean isSameYear(Calendar cal1, Calendar cal2) {
        return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR);
    }
} 